package org.arch_learn.dubbo_demo.dubbo_spi_threadpool_demo;


import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.*;


public class WatchingThreadPool extends FixedThreadPool implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(WatchingThreadPool.class);

    //定义线程池阈值
    private static final double ALARM_PERCENT = 0.90;
    private static Map<URL, ThreadPoolExecutor> THREAD_POOLS = new ConcurrentHashMap<>();

    public WatchingThreadPool() {
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(this, 1, 3, TimeUnit.SECONDS);
    }

    //通过父类创建线程池
    @Override
    public Executor getExecutor(URL url) {
        Executor executor = super.getExecutor(url);
        if (executor instanceof ThreadPoolExecutor) {
            THREAD_POOLS.put(url, (ThreadPoolExecutor) executor);
        }
        return executor;
    }

    @Override
    public void run() {
        THREAD_POOLS.entrySet().forEach(entry -> {
            URL url = entry.getKey();
            ThreadPoolExecutor executor = entry.getValue();
            int activeCount = executor.getActiveCount();
            int corePoolSize = executor.getCorePoolSize();
            double usedPercent = activeCount / (corePoolSize * 1.0);
            LOGGER.info("线程池执行状态：[{}/{}:{}%]", activeCount, corePoolSize, usedPercent * 100);
            if (usedPercent > ALARM_PERCENT) {
                LOGGER.error("超出警戒线：host：{}，当前使用率是：{}，URL：{}", url.getHost(), usedPercent * 100, url);
            }
        });
    }
}
